<?php
global $Config;
require_once($Config->WebCMSRoot.'Base/Model.php');
require_once($Config->WebCMSRoot.'Data/Content.php');

Class ContentModel extends BaseModel
{
	var $Key;
	var $Content;

	function ContentModel($array = null)
	{
		$this->Key     = '';
		$this->Content = '';
		
		if (isset($array))
		{
			$this->Key = $array['Key'];
			$this->Content = stripslashes($array['Content']);

			parent::BaseModel($array['ID']);
		}
		else
		{
			parent::BaseModel();
		}
	}
	
	function Retrieve(&$parameters)
	{
		$db = new ContentData();
		$this->Parameters = &$parameters;
//print('<pre>'.var_export($parameters, true).'</pre>');exit;
		
		$this->ID      = $this->GetParameter('id');
		$this->Key     = $this->GetParameter('key');
		$this->Content = $this->GetParameter('content');
		
//print('<pre>'.var_export($this, true).'</pre>');exit;
		if ($this->ID != -1)
		{
			$db->Retrieve(&$this);
		}
		else
		{
			$content = new ContentModel();
			$content->Key = $this->Key;
			$this->Collection[0] = $content;
		}
//print('<pre>'.var_export($this, true).'</pre>');exit;
	}

	function Persist()
	{
		$db = new ContentData();

		$db->Update(&$this);
	}
	
	function Delete()
	{
		$db = new ContentData();
		$db->Delete(&$this);
	}
	
	/* Extended functions */
	function Unescape($iconv_to = 'UTF-8')
	{
		$source = $this->Content;

		// escape  \", \'
		$source = preg_replace ('|\\\\"|', '"', $source);
		$source = preg_replace ('|\\\\\'|', '\'', $source);

		$decodedStr = '';
		$pos = 0;
		$len = strlen ($source);
		
		while ($pos < $len)
		{
			$charAt = substr ($source, $pos, 1);
			if ($charAt == '%')
			{
				$pos++;
				$charAt = substr ($source, $pos, 1);
				if ($charAt == 'u')
				{
					// we got a unicode character
					$pos++;
					$unicodeHexVal = substr ($source, $pos, 4);
					$unicode = hexdec ($unicodeHexVal);
					$decodedStr .= code2utf($unicode);
					$pos += 4;
				}
				else
				{
					// we have an escaped ascii character
					$hexVal = substr ($source, $pos, 2);
					$decodedStr .= chr (hexdec ($hexVal));
					$pos += 2;
				}
			}
			else
			{
				$decodedStr .= $charAt;
				$pos++;
			}
		}

		if ($iconv_to != "UTF-8")
		{
			$decodedStr = iconv("UTF-8", $iconv_to, $decodedStr);
		}
	  
		return $this->Content = $decodedStr;
	}

	/**
	* Function coverts number of utf char into that character.
	* Function taken from: http://sk2.php.net/manual/en/function.utf8-encode.php#49336
	*
	* @param int $num
	* @return utf8char
	*/
	function code2utf($num)
	{
		if($num<128)return chr($num);
		if($num<2048)return chr(($num>>6)+192).chr(($num&63)+128);
		if($num<65536)return chr(($num>>12)+224).chr((($num>>6)&63)+128).chr(($num&63)+128);
		if($num<2097152)return chr(($num>>18)+240).chr((($num>>12)&63)+128).chr((($num>>6)&63)+128) .chr(($num&63)+128);
		return '';
	}	
}
?>